package com.tarena.lbs.attach.rpc;

import com.tarena.lbs.attach.api.AttachApi;
import com.tarena.lbs.attach.pojo.dto.AttachDTO;
import com.tarena.lbs.attach.pojo.dto.AttachQrDTO;
import com.tarena.lbs.attach.pojo.param.AttachQRParam;
import com.tarena.lbs.attach.pojo.param.PicUpdateParam;
import com.tarena.lbs.attach.pojo.query.AttachQuery;
import com.tarena.lbs.attach.service.AttachService;
import com.tarena.lbs.base.protocol.exception.BusinessException;
import com.tarena.lbs.common.principle.UserPrinciple;
import com.tarena.lbs.common.utils.AuthenticationContextUtils;
import com.tarena.lbs.common.utils.JsonUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.rpc.RpcContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;

import java.util.List;

@DubboService
@Slf4j
public class AttachRpcService implements AttachApi {

    private final AttachService attachService;

    // 构造器注入
    public AttachRpcService(AttachService attachService) {
        this.attachService = attachService;
    }

    @Override
    public List<AttachDTO> getAttachInfo(AttachQuery attachQuery) {
        return attachService.getAttachInfo(attachQuery);
    }

    @Override
    public boolean batchUpdateBusiness(List<PicUpdateParam> picParams) {
        return attachService.batchUpdateBusiness(picParams);
    }

    @Override
    public boolean deleteAttachInfo(String fileUuid) {
        return attachService.deleteAttachInfo(fileUuid);
    }

    @Override
    public AttachQrDTO generateQrCode(AttachQRParam attachQRParam)  {
        try {
            // 从Dubbo上下文获取用户信息
            String userInfoJson = RpcContext.getContext().getAttachment("userInfo");
            if (StringUtils.isNotBlank(userInfoJson)) {
                try {
                    UserPrinciple userPrinciple = JsonUtils.fromJson(userInfoJson, UserPrinciple.class);
                    AuthenticationContextUtils.save(userPrinciple);
                    log.info("从Dubbo上下文获取用户信息成功，用户ID：{}", userPrinciple.getId());
                } catch (Exception e) {
                    log.error("解析用户信息失败：{}", e.getMessage(), e);
                }
            } else {
                log.warn("Dubbo上下文中未找到用户信息");
            }
            
            return attachService.generateQrCode(attachQRParam);
        } catch (BusinessException e) {
            throw new RuntimeException(e);
        } finally {
            // 清理ThreadLocal中的用户信息
            AuthenticationContextUtils.clear();
        }
    }

    @Override
    public List<AttachDTO> bindPic(List<PicUpdateParam> picParams)  {
        try {
            return attachService.bindPic(picParams);
        } catch (BusinessException e) {
            throw new RuntimeException(e);
        }
    }




}